use std::collections::HashMap;
use maxminddb::geoip2::City;
use maxminddb::Reader;
use serde_json::json;
use tokio::net::TcpStream;
use tracing::{debug, info, warn};
use uuid::Uuid;
use crate::http::{get_gio, get_global_gio, init_global_gio};
use crate::http::http_request::HttpRequest;
use crate::http::http_response::HttpResponse;
use crate::nosql::nosql_database::NoSqlValue;
use crate::util::cookie_parse::cookie_parse;
use crate::util::date_util::{get_current_date, get_current_date_plus_ten_days};

pub fn do_filter(request: &HttpRequest, response: &mut HttpResponse, socket: &TcpStream) {

    let cookie = cookie_parse(request);

    if let Some(session_id) = cookie.get("session_id") {
        debug!("session_id start : {}", session_id);


        // 安全地访问 GIO_CLIENT
        let mut client_guard = get_gio().read().unwrap();
        // let user_json = client_guard.get(session_id).unwrap();
        if let Some(user) = client_guard.get(session_id) {
            info!("user: {}", user);
        } else {
            response.headers.insert("Set-Cookie".to_string(), format!("session_id={}; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/; HttpOnly", session_id));
            info!("user not found");
        }
        // debug!("session_id end : {}", user_json);
    } else {


        let peer_addr = socket.peer_addr().expect("Failed to get peer address");

        if peer_addr.ip().is_loopback() {
            warn!("Client is connecting from loopback address: {}", peer_addr);
        }

        info!("Client connected from: {}", peer_addr.ip());

        let reader = Reader::open_readfile("public/data/geoip2/GeoLite2-City.mmdb").expect("找不到数据库文件");

        let mut city_ip = "unknown";

        let mut subdivision_ip = "unknown";

        let ip = peer_addr.ip();

        match reader.lookup::<City>(ip) {
            Ok(result) => {
                if let Some(result)  =  result{
                    if let Some(city) = result.city {
                        if let Some(names) = city.names {
                            let city_name = names.get("zh-CN");
                            if let Some(city_name_ip) = city_name {
                                city_ip = city_name_ip;
                            }
                        }
                    }

                    if let Some(subdivision) = result.subdivisions {
                        subdivision.iter().for_each(|subdivision| {
                            if let Some(names) = &subdivision.names {
                                if let Some(subdivision_name) = names.get("zh-CN") {
                                    subdivision_ip = subdivision_name;
                                }
                            }
                        });
                    }
                }
            }
            Err(_) => {
                warn!("Failed to lookup IP address in database");
            }
        }




        let session_id = Uuid::new_v4();

        let name = "游客".to_owned() + &*session_id.to_string();

        let user = json!({
            "session_id": session_id.to_string(),
            "name": name,
            "messages": [],
            "ip": peer_addr.ip().to_string(),
            "city": city_ip,
            "province": subdivision_ip,
        });

        let user_json = serde_json::to_string(&user).unwrap_or_else(|_| String::from("{}"));
        // 安全地访问 GIO_CLIENT
        let mut client_guard = get_gio().write().unwrap();
        client_guard.insert(session_id.to_string(), user_json);

        response.headers.insert("Set-Cookie".to_string(), format!("session_id={}; Expires={}; Path=/; HttpOnly", session_id, get_current_date_plus_ten_days()));

        debug!("new session_id : {}", session_id);

    }
}

